package org.vacoor.xqq.core.mod;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.vacoor.xqq.core.bean.ChatToken;
import org.vacoor.xqq.core.http.HttpRequestor;
import org.vacoor.xqq.core.http.Request;
import org.vacoor.xqq.core.http.RequestCallbackAdapter;
import org.vacoor.xqq.core.http.Response;
import org.vacoor.xqq.core.msg.req.ReplyMsg;
import org.vacoor.xqq.core.util.Jacksons;

import java.io.IOException;
import java.util.Date;
import java.util.concurrent.atomic.AtomicLong;

/**
 * User: vacoor
 */
public class MessageSender {
    private static final Logger logger = LoggerFactory.getLogger(MessageSender.class);

    public static final String SEND_CONTACT_MSG_URL = "http://d.web2.qq.com/channel/send_buddy_msg2";
    public static final String SEND_GROUP_MSG_URL = "http://d.web2.qq.com/channel/send_qun_msg2";
    public static final String SEND_DISCU_MSG_URL = "http://d.web2.qq.com/channel/send_discu_msg2";

    private ChatToken token;
    //    public long msgId;
    private AtomicLong msgId;
    private boolean tip = true;


    public MessageSender(ChatToken token) {
        this.token = token;

        // 按照腾讯做法来生成初始的 MSG ID (使用当前时间13位毫秒的倒数4,5,6位)
        this.msgId = new AtomicLong(new Date().getTime() / Math.round(1E3) % Math.round(1E4) * Math.round(1E4));
    }

    public long sendContactMsg(ReplyMsg msg) {
        logger.debug("Send contact onMsg: {}", msg);

        String jsonMsg = Jacksons.createObjectNode()
                .put("to", msg.getTo())
                .put("face", msg.getFace())
                .put("clientid", token.getClientId())
                .put("msg_id", msgId.incrementAndGet())
                .put("psessionid", token.getPsessionId())
                // msgBody 为数组的字符串形式, 且中文使用Unicode "[]"
                .put("content", Jacksons.serialize(msg.getMsgBody()))
                .toString();


        logger.debug("发送消息: {}", jsonMsg);
        HttpRequestor.getInstance().send(
                new Request(SEND_CONTACT_MSG_URL, Request.HttpMethod.POST)
                        .addHeader("Referer", "http://d.web2.qq.com/proxy.html?v=20130916001&callback=1&id=3")
                        .addHeader("MsgBody-Type", "application/x-www-form-urlencoded; charset=UTF-8")
                        .addParameter("r", jsonMsg),
                new RequestCallbackAdapter() {
                    @Override
                    public void onSuccess(Response resp) {
                        try {
                            // TODO 也可能返回120/ 121 被踢出
                            logger.debug("消息发送完成, 响应: {}", resp.getContent().asString());
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
        );
        return msgId.longValue();
    }

    /**
     * {"group_uin":1652356398,"msgBody":"[\"a\",\"\",[\"font\",{\"name\":\"$(BAWBN(B\",\"size\":\"22\",\"richStyle\":[0,0,0],\"color\":\"000000\"}]]","msg_id":46580001,"clientid":"81658923","psessionid":"8368046764001e636f6e6e7365727665725f77656271714031302e3132382e36362e31313500005e7b00000499026e04007cb6ec836d0000000a40487375683145746c566d00000028414629766209ca5a7052c8b135d4f190ac8508150e35f0f906daa1ef29d4cff7ca255a1d8769e7b0"}
     * group_uin:
     * msgBody:
     * msg_id:
     * clientid:
     * psessionid
     */
    public long sendGroupMsg() {
        return 1;
    }

    /**
     * {"did":"1636278456","msgBody":"[\"a\",\"\",[\"font\",{\"name\":\"$(BAWBN(B\",\"size\":\"22\",\"richStyle\":[0,0,0],\"color\":\"000000\"}]]","msg_id":46580002,"clientid":"81658923","psessionid":"8368046764001e636f6e6e7365727665725f77656271714031302e3132382e36362e31313500005e7b00000499026e04007cb6ec836d0000000a40487375683145746c566d00000028414629766209ca5a7052c8b135d4f190ac8508150e35f0f906daa1ef29d4cff7ca255a1d8769e7b0"}
     * did:
     * ...
     * @return
     */
    public long sendDiscuMsg() {
        return 1;
    }
}
